﻿using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using System.IO;
namespace VisionCloud.Domain
{
    /// <summary>
    /// 实现 IModelBinder接口，在这个类里完成从Http请求中获取数据到模型的过程
    /// </summary>
    public class MyModelBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            string key = bindingContext.ModelName;

            if (String.IsNullOrEmpty(key))
            {
                key = bindingContext.FieldName;
            }

            var request = bindingContext.HttpContext.Request;
            var stream = new StreamReader(request.Body);
            var body = stream.ReadToEnd();
            string name = bindingContext.ModelType.Name;
            string fullName = bindingContext.ModelType.FullName;



            string val = string.Empty;


            
            if (bindingContext.Model != null)
            {
                bindingContext.Result = ModelBindingResult.Success(bindingContext.Model);
            }

            if (bindingContext.ModelType == typeof(IFormFile))
            {
                bindingContext.Model = bindingContext.HttpContext.Request.Form.Files[0];
            }

            bindingContext.Result = ModelBindingResult.Success(bindingContext.Model);

            return Task.CompletedTask;
        }
    }
}
